package john.wenzi.server.filter;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import john.wenzi.server.servlet.DownloadServlet;
import john.wenzi.server.utils.RSAUtil;

public class PermissionCheckFilter implements Filter{

	public static Logger logger = LoggerFactory.getLogger(PermissionCheckFilter.class);
	
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain arg2)
			throws IOException, ServletException {
		logger.info("权限校验开始");
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) resp;
		
		String sid = request.getHeader("X-SID");
		String signature = request.getHeader("X-Signature");
		//公钥
	    File publicFile = new File("ppk/public.ppk");
	    Long filelength = publicFile.length();
        byte[] fileByte = new byte[filelength.intValue()];
        FileInputStream is = new FileInputStream(publicFile);
        is.read(fileByte);
        String publicKey = new String(fileByte);
        //进行权限验证
        if(RSAUtil.doCheck(sid, signature, publicKey)) {
        	logger.info("权限校验成功");
        	arg2.doFilter(request, response);
        }else {
        	logger.info("权限校验失败");
        	response.setStatus(403);
        }
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
	}

}
